package com.rc.saas.tenant.controller.shop;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.shop.*;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.ugs.UgsMemberPointRecord;
import com.rc.saas.tenant.model.ugs.UgsMemberPointRecordExample;
import com.rc.saas.tenant.search.shop.ShopOrderSearch;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.shop.*;
import com.rc.saas.tenant.service.ugs.UgsMemberPointRecordService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.shop.ShopOrderResultVo;
import com.rc.saas.tenant.vo.shop.ShopOrderStatisticsVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/shopOrder")
public class ShopOrderController {
    private static Logger logger = LogManager.getLogger(ShopOrderController.class);

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private ShopOrderReturnApplyService shopOrderReturnApplyService;

    @Autowired
    private ShopOrderGoodsService shopOrderGoodsService;

    @Autowired
    private ShopGoodsService shopGoodsService;

    @Autowired
    private ShopStockRecordService shopStockRecordService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private UgsMemberPointRecordService ugsMemberPointRecordService;

    /**
     * 跳转积分商城订单管理页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String shopOrderInfoPage(Model model) {
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        return "/templates/shop/shopOrdered";
    }

    /**
     * 返回订单列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listShopOrder", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listShopOrder(ShopOrderSearch shopOrderSearch) {
        PageInfo<ShopOrderResultVo> pageInfo = shopOrderService.listPageByCondition(shopOrderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 返回商城订单状态信息
     *
     * @return
     */
    @RequestMapping(value = "/selectShopOrderStatistics", method = RequestMethod.GET)
    @ResponseBody
    public TResponse selectShopOrderStatistics() {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        ShopOrderStatisticsVo shopOrderStatisticsVo = shopOrderService.selectShopOrderStatistics(tenantUser.getTenantCode());
        return TResponse.SUCCESS_DATA(shopOrderStatisticsVo);
    }

    /**
     * 保存发货信息
     *
     * @return
     */
    @RequestMapping(value = "/updateShopOrderInfo", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateShopOrderInfo(Long shopOrderId, String shippingNo, String deliverExpress) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        TResponse tResponse = TResponse.SUCCESS();
        if (StringUtil.isBlank(shippingNo) || StringUtil.isBlank(deliverExpress)) {
            return TResponse.FAIL("请填写相关信息");
        }
        try {
            tResponse = shopOrderService.updateShopOrderInfo(shopOrderId, shippingNo, deliverExpress, tenantUser);
            return tResponse;
        } catch (Exception e) {
            logger.error("保存发货信息失败", e);
            return TResponse.FAIL("保存发货信息失败");
        }
    }

    /**
     * 根据商品订单ID返回订单信息
     *
     * @param shopOrderId
     * @return
     */
    @RequestMapping(value = "/selectShopOrderInfo", method = RequestMethod.GET)
    @ResponseBody
    public TResponse selectShopOrderInfo(Long shopOrderId) {
        ShopOrderResultVo shopOrderResultVo = shopOrderService.selectShopOrderInfo(shopOrderId);
        return TResponse.SUCCESS_DATA(shopOrderResultVo);
    }

    /**
     * 修改订单状态
     *
     * @param shopOrderId 商品订单ID
     * @param method      修改方式 0:确认收货；1：通过退货申请；2：驳回退货申请；3：退货已收
     * @param remark      退货驳回备注
     * @return
     */
    @RequestMapping(value = "/updateShopOrderStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateShopOrderStatus(Long shopOrderId, String method, String remark) {
        TenantUser user = ShiroUtils.getSessionUser();
        ShopOrder shopOrder = shopOrderService.selectByPrimaryKey(shopOrderId);

        //退货申请记录（有效关联）
        ShopOrderReturnApply shopOrderReturnApply = shopOrderReturnApplyService.selectShopOrderReturnApplyByShopOrderId(shopOrderId);

        ShopOrderGoodsExample example = new ShopOrderGoodsExample();
        example.createCriteria().andShopOrderIdEqualTo(shopOrderId);
        ShopOrderGoods shopOrderGoods = shopOrderGoodsService.selectByExample(example).get(0);

        ShopGoods shopGoods = shopGoodsService.selectByPrimaryKey(shopOrderGoods.getGoodsId());

        //下单数量
        Integer goodsNum = shopOrderGoods.getGoodsNum();
        //库存数量
        Integer stockNum = shopGoods.getStockNum();

        try {
            if ("0".equals(method)) {
                //确认收货
                shopOrder.setReceiverTime(new Date());
                shopOrder.setStatus("3");
            } else if ("1".equals(method)) {
                if ("0".equals(shopOrderReturnApply.getGoodsStatus())) {
                    //待发货订单
                    shopOrder.setStatus("7");
                    shopOrderReturnApply.setStatus("2");

                    //修改商品锁定库存
                    shopGoods.setStockLockedCount(shopGoods.getStockLockedCount()-goodsNum);
                    shopGoods.setLastUpdatedBy(user.getLoginName());
                    shopGoods.setLastUpdatedTime(new Date());
                    shopGoodsService.updateByPrimaryKeySelective(shopGoods);

                    MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(shopOrder.getMemberId());
                    //修改会员账户member_account
                    MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(shopOrder.getMemberId());
                    memberAccount.setPoint(memberAccount.getPoint() + shopOrder.getUsePoint());
                    memberAccount.setLastUpdatedBy(user.getLoginName());
                    memberAccount.setLastUpdatedTime(new Date());
                    memberAccountService.updateByPrimaryKeySelective(memberAccount);

                    //退货退回积分
                    UgsMemberPointRecord ugsMemberPointRecord = new UgsMemberPointRecord();
                    ugsMemberPointRecord.setTenantCode(shopOrder.getTenantCode());
                    ugsMemberPointRecord.setMemberId(shopOrder.getMemberId());
                    ugsMemberPointRecord.setMemberType(memberInfo.getMemberType());
                    ugsMemberPointRecord.setRecordType("6");
                    ugsMemberPointRecord.setShopOrderId(shopOrderId);
                    ugsMemberPointRecord.setShopOrderNum(shopOrder.getShopOrderNum());
                    ugsMemberPointRecord.setPoint(shopOrder.getUsePoint());

                    UgsMemberPointRecordExample ugsMemberPointRecordExample = new UgsMemberPointRecordExample();
                    ugsMemberPointRecordExample.createCriteria().andMemberIdEqualTo(shopOrder.getMemberId());
                    ugsMemberPointRecordExample.setOrderByClause("created_time desc");
                    List<UgsMemberPointRecord> ugsMemberPointRecords = ugsMemberPointRecordService.selectByExample(ugsMemberPointRecordExample);
                    if (!CollectionUtils.isEmpty(ugsMemberPointRecords)) {
                        ugsMemberPointRecord.setResult(ugsMemberPointRecords.get(0).getResult() + shopOrder.getUsePoint());
                        ugsMemberPointRecord.setPointTypeId(ugsMemberPointRecords.get(0).getPointTypeId());
                    }
                    ugsMemberPointRecord.setRemark("商品退货退回积分");
                    ugsMemberPointRecord.setCreatedBy(user.getLoginName());
                    ugsMemberPointRecord.setCreatedTime(new Date());
                    ugsMemberPointRecordService.insertSelective(ugsMemberPointRecord);

                } else if ("1".equals(shopOrderReturnApply.getGoodsStatus())) {
                    //已发货订单
                    shopOrder.setStatus("6");
                    shopOrderReturnApply.setStatus("1");

                }
                shopOrderReturnApply.setLastUpdatedBy(user.getLoginName());
                shopOrderReturnApply.setLastUpdatedTime(new Date());
                shopOrderReturnApplyService.updateByPrimaryKeySelective(shopOrderReturnApply);

            } else if ("2".equals(method)) {
                //驳回退货申请
                shopOrderReturnApply.setStatus("3");
                shopOrderReturnApply.setRemark(remark);
                shopOrderReturnApply.setLastUpdatedBy(user.getLoginName());
                shopOrderReturnApply.setLastUpdatedTime(new Date());
                shopOrderReturnApplyService.updateByPrimaryKeySelective(shopOrderReturnApply);
                if ("0".equals(shopOrderReturnApply.getGoodsStatus())) {
                    shopOrder.setStatus("1");
                } else if ("1".equals(shopOrderReturnApply.getGoodsStatus())) {
                    shopOrder.setStatus("2");
                } else if ("2".equals(shopOrderReturnApply.getGoodsStatus())) {
                    shopOrder.setStatus("3");
                }
                //shopOrder.setStatus(shopOrderReturnApply.getGoodsStatus());
            } else if ("3".equals(method)) {
                //修改商品信息
                shopGoodsService.updateShopGoods(shopOrderId, user);
                //退货已收
                shopOrder.setStatus("7");
            }
            shopOrder.setLastUpdatedBy(user.getLoginName());
            shopOrder.setLastUpdatedTime(new Date());
            shopOrderService.updateByPrimaryKeySelective(shopOrder);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("操作失败", e);
            return TResponse.FAIL("操作失败");
        }
    }
}
